<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param QueryExecuted $event
     * @return mixed
     */
    public function handle(QueryExecuted $event)
    {
        // 非生产或调试模式，记录全局SQL执行语句
        if (!isProd() || isAccess()) {
            $log = $event->sql;
            if (false !== strpos($event->sql, '?')) {
                $sql = str_replace("?", "'%s'", $event->sql);
                $log = vsprintf($sql, $event->bindings ?? []);
            }
            if (false !== strpos($log, 'telescope') ||
                false !== stripos($log, 'show tables') ||
                false !== strpos($log, 'syslog_frontend_')
            ) {
                return false;
            }
            Log::channel('sql')->info($log . ';');
        }
        return true;
    }
}
